package com.wangdong.network.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * 对文件处理的工具类
 * 
 * @author Tony
 *
 */
public class FileUtils {
	
	/**
	 * 获取可以使用的缓存目录
	 * @param context
	 * @return
	 */
    public static File getDiskCacheDir(Context context) {
        final String cachePath = checkSDCard() ? getExternalCacheDir(context).getPath() : getAppCacheDir(context);

        File cacheDirFile = new File(cachePath);
        if (!cacheDirFile.exists()) {
            cacheDirFile.mkdirs();
        }

        return cacheDirFile;
    }
    
    /**
     * 获取程序外部的缓存目录
     * @param context
     * @return
     */
     public static File getExternalCacheDir(Context context) {
     	// 这个sd卡中文件路径下的内容会随着，程序卸载或者设置中清除缓存后一起清空
         final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
         return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
     }
     
     /**
      * 获取文件路径空间大小
      * @param path
      * @return
      */
     public static long getUsableSpace(File path) {
     	try{
     		 final StatFs stats = new StatFs(path.getPath());
     	     return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
     	}catch (Exception e) {
 			e.printStackTrace();
 			return -1;
 		}
        
     }

	/**
	 * 判断文件是否存在
	 * @return
	 */
	public static boolean fileIsExists(Context context, String fileName){
		try{
            File download = context.getExternalFilesDir("Download");
            File f=new File(download.getAbsolutePath()+"/"+fileName);
			if(!f.exists()){
				return false;
			}
		}catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}
	/**
	 * 获取文件
	 */
	public static File getFile(Context context, String fileName){
		File f=null;
		try{
			File download = context.getExternalFilesDir("Download");
			f=new File(download.getAbsolutePath()+"/"+fileName);
			if(!f.exists()){
				return null;
			}
		}catch (Exception e) {
			// TODO: handle exception
			return null;
		}
		return f;
	}
     /**
 	 * 空间大小单位格式化
 	 * @param size
 	 * @return
 	 */
 	public static String formatSize(long size) {
         String suffix = null;
         float fSize=0;

         if (size >= 1024) {
             suffix = "KB";
             fSize=size / 1024;
             if (fSize >= 1024) {
                 suffix = "MB";
                 fSize /= 1024;
             }
             if (fSize >= 1024) {
                 suffix = "GB";
                 fSize /= 1024;
             }
         } else {
             fSize = size;
         }
         
         java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
         StringBuilder resultBuffer = new StringBuilder(df.format(fSize));
         if (suffix != null)
             resultBuffer.append(suffix);
         return resultBuffer.toString();
     }
    
	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public static boolean checkSDCard() {
		final String status = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(status)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 获取安装在用户手机上的com.youyuan.yyapp下的files目录
	 * 
	 * @return files path
	 */
	public static String getAppFilesDir(Context context) {
		return context.getFilesDir().getAbsolutePath();
	}
	
	/**
	 * 获取安装在用户手机上的com.youyuan.yyapp下的cache目录
	 * 
	 * @return cache path
	 */
	public static String getAppCacheDir(Context context) {
		return context.getCacheDir().getPath();
	}

	   /* @param srcPath : 源文件全路径
	     * @param destPath : 目标文件全路径
	     * @return
	     */
	    public static long copyFile(String srcPath, String destPath) {
	        try {
	            int position = destPath.lastIndexOf(File.separator);
	            String dir = destPath.substring(0, position);
	            String newFileName = destPath.substring(position+1);
	            final File cacheDir = new File(dir);
	            if (!cacheDir.exists()) {
	                cacheDir.mkdirs();
	            }
	            return copyFile(new File(srcPath), new File(dir), newFileName);
	        } catch (Exception e) {
	            return 0;
	        }

	    }
	    /**
	     * 复制文件(以超快的速度复制文件)
	     * 
	     * @param srcFile
	     *            源文件File
	     * @param destDir
	     *            目标目录File
	     * @param newFileName
	     *            新文件名
	     * @return 实际复制的字节数，如果文件、目录不存在、文件为null或者发生IO异常，返回-1
	     */
	    @SuppressWarnings("resource")
	    public static long copyFile(final File srcFile, final File destDir, String newFileName) {
	        long copySizes = 0;
	        if (!srcFile.exists()) {	          
	            copySizes = -1;
	        } else if (!destDir.exists()) {	           
	            copySizes = -1;
	        } else if (newFileName == null) {	           
	            copySizes = -1;
	        } else {
	            FileChannel fcin = null;
	            FileChannel fcout = null;
	            try {
	                fcin = new FileInputStream(srcFile).getChannel();
	                fcout = new FileOutputStream(new File(destDir, newFileName)).getChannel();
	                long size = fcin.size();
	                fcin.transferTo(0, fcin.size(), fcout);
	                copySizes = size;
	            } catch (FileNotFoundException e) {
	                e.printStackTrace();
	            } catch (IOException e) {
	                e.printStackTrace();
	            } finally {
	                try {
	                    if (fcin != null) {
	                        fcin.close();
	                    }
	                    if (fcout != null) {
	                        fcout.close();
	                    }
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return copySizes;
	    }
}
